<?php

namespace Home\Controller;

use Home\Service\WordpressSyncerService;


class UserController extends BaseController
{
    public function index()
    {
        $this->display();
    }

    public function login()
    {
        if (IS_POST && tpx_config_get('cas_login_enable', false)) {
            return $this->error('CAS已经配置,不允许登录');
        }
        if (IS_POST && tpx_config_get('wordpress_syncer_enable')) {

            // 首先尝试本地登录，如果没有登录
            $username = I('post.username', '', 'trim');
            $password = I('post.password');

            $ret = WordpressSyncerService::login($username, $password, $logined_uid);

            if (true !== $ret) {
                $this->error($ret);
            }

            // 登录用户
            $_SESSION ['member_user_uid'] = $logined_uid;
            $redirect = I('session.login_redirect', U('User/profile'));
            if (isset($_SESSION['login_redirect'])) {
                unset($_SESSION['login_redirect']);
            }
            $this->success('', $redirect);

        }

        include './app/Home/Controller/Modules/UserLoginUsernamePassword.php';
    }

    public function register()
    {
        if (tpx_config_get('cas_login_enable', false)) {
            return $this->error('CAS已经配置,不允许登录');
        }
        if (tpx_config_get('wordpress_syncer_enable')) {
            $this->error('Wordpress同步已开启，禁止注册');
        }
        if (IS_POST) {
            $username = I('post.username', '', 'trim');
            $password = I('post.password');
            $password_repeat = I('post.password-repeat');

            if ($password != $password_repeat) {
                $this->error('两次密码输入不一致');
            }
            $ret_uid = null;
            $msg = $this->_am->register($email = '', $cellphone = '', $username, $password, $add_data = array(), $ret_uid);
            if (true === $msg) {
                cookie('docmz_user_intro', 1, array('expire' => 365 * 24 * 3600, 'httponly' => false, 'path' => __ROOT__));
                $this->success('', U('User/login'));
            } else {
                $this->error($msg);
            }
        }
        if (empty($title)) {
            $title = tpx_config_get('home_title', '');
        }
        $this->assign('page_title', '新用户注册 - ' . $title);
        $this->assign('page_keywords', '新用户注册,' . $title . '注册');
        $this->assign('page_description', '注册成为' . $title . '新用户');
        $this->display();
    }

    public function logout()
    {
        if (tpx_config('cas_login_enable')) {
            $this->doCAS('logout');
            return;
        }
        unset ($_SESSION ['member_user_uid']);
        $this->success('ok');
    }

    public function changepwd()
    {
        if (tpx_config_get('cas_login_enable', false)) {
            return $this->error('CAS已经配置,不允许登录');
        }
        if (tpx_config_get('wordpress_syncer_enable')) {
            $this->error('Wordpress同步已开启，禁止修改密码');
        }
        include './app/Home/Controller/Modules/UserChangepwd.php';
    }

    public function profile()
    {
        if (IS_POST) {

            $profile = array();
            $profile['realname'] = I('post.profile_realname', '', 'trim');
            $this->_am->update('profile', $profile);

            $extra_info = array();
            $doc_header_image = I('post.doc_header_image', '', 'trim');
            if (is_upload_temp_file($doc_header_image)) {
                $extra_info['doc_header_image'] = 'data/image/' . upload_tempfile_save_storage('image', $doc_header_image);
                $doc_header_image_old = $this->_am->get('extra_info.doc_header_image');
                if (!empty($doc_header_image_old)) {
                    safe_delete_storage_file($doc_header_image_old);
                }
                $this->_am->update('extra_info', $extra_info);
            }
            $this->success('OK');
        }
        $this->display();
    }

    public function load_profile()
    {
        $data = array();

        $data['username'] = $this->_am->get('user.username');
        $data['upload_space_space'] = byte_format(intval($this->_am->get('upload_space.space')));

        $one = D('MemberUpload')->table('__MEMBER_UPLOAD__ mu')->join('__DATA_FILES__ df ON df.id=mu.data_id')
            ->field('sum(df.filesize) as total')->where(array('mu.uid' => MEMBER_LOGINED_UID))->find();
        $upload_size_current = $one['total'];

        $data['upload_space_used'] = byte_format($upload_size_current);

        $data['profile_realname'] = $this->_am->get('profile.realname');

        $data['doc_header_image'] = $this->_am->get('extra_info.doc_header_image');
        if (empty($data['doc_header_image'])) {
            $data['doc_header_image'] = tpx_config_get('docmz_pdf_logo', 'asserts/res/img/pdf_logo.png');
        }

        $this->ajaxReturn(array(
            'status' => 1,
            'data' => $data
        ));
    }

    public function cas()
    {
        $this->doCAS('login');
    }

    protected function doCAS($type = 'login')
    {
        if (!tpx_config('cas_login_enable')) {
            return $this->error('您未开启CAS登录');
        }

        include './app/Common/Extends/phpCAS/CAS.php';

        //  CAS Server 主机
        $cas_host = tpx_config_get('cas_login_host', '');

        // CAS Server 路径
        $cas_context = tpx_config_get('cas_login_path', '');

        // CAS server.端口
        $cas_port = intval(tpx_config_get('cas_login_port', 443));

        // <span>CAS Server </span>证书
        //$cas_server_ca_cert_path = './ssoserver.cer';

        // Enable debugging
        \phpCAS::setDebug();

        // Initialize phpCAS
        \phpCAS::client(CAS_VERSION_3_0, $cas_host, $cas_port, $cas_context);

        // For production use set the CA certificate that is the issuer of the cert
        // on the CAS server and uncomment the line below
        // phpCAS::setCasServerCACert($cas_server_ca_cert_path);
        // phpCAS::setCasServerCACert($cas_server_ca_cert_path, false);

        // For quick testing you can disable SSL validation of the CAS server.
        // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
        // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
        \phpCAS::setNoCasServerValidation();

        // force CAS authentication
        \phpCAS::forceAuthentication();

        $username = \phpCAS::getUser();

        switch ($type) {
            case 'login':
                $userFind = D('MemberUser')->where(array('username' => $username))->find();
                if (empty($userFind)) {
                    // 注册新用户
                    $ret_uid = 0;
                    $msg = $this->_am->register($email = '', $cellphone = '', $username, time(), $add_data = array(), $ret_uid);
                    if (true === $msg) {
                        $_SESSION ['member_user_uid'] = $ret_uid;
                        //跳转
                        $redirect = I('session.login_redirect', U('User/profile'));
                        if (isset($_SESSION['login_redirect'])) {
                            unset($_SESSION['login_redirect']);
                        }
                        header('Location: ' . $redirect);
                    } else {
                        $this->error($msg);
                    }
                } else {
                    // 老用户登录
                    $_SESSION ['member_user_uid'] = $userFind['uid'];
                    // 跳转
                    $redirect = I('session.login_redirect', U('User/profile'));
                    if (isset($_SESSION['login_redirect'])) {
                        unset($_SESSION['login_redirect']);
                    }
                    header('Location: ' . $redirect);
                }
                break;
            case 'logout':
                \phpCAS::logout();
                break;
        }
    }
}